<?php
namespace Home\Controller;

use Think\Controller;

class CrontabController extends CommonController
{
    // 此key内部调用，模拟支付
    private $key = '270fd093ee8a9bf8ae';

    public function __construct()
    {
        parent::__construct();

        // 无限时运行
        set_time_limit(0);

        $key = I('get.key', '', 'trim');
        if ($key != $this->key) {
            die('您无此权限');
        }

        // 日志记录
        file_put_contents(WEB_PATH . '/Uploads/Crontab/' . date('Ymd') . '.txt', print_r($this->data, true), FILE_APPEND);
    }

    // 红包过期退回
    public function redReback()
    {
        $where = [
            'out_time'      => ['lt', CUR_DATETIME],
            'remain_number' => ['neq', 0],
        ];

        $reds = M('red_bag')->where($where)->limit(false)->select();

        if ($reds) {
            foreach ($reds as $red) {

                begin();
                $result1 = M('red_bag')->where(['id' => $red['id']])->save(['status' => 4]);
                $result2 = D('user', 'Service')->moneyLog($red['user_id'], $red['remain_money'], '红包未领取退回');

                if ($result1 && $result2) {
                    commit();
                } else {
                    rollback();
                }
            }
        }
        die('运行完成');
    }
}
